#ifndef _ALLOCATOR_H_INCLUDED_
#define _ALLOCATOR_H_INCLUDED_

#include <GlobalData.h>
#include <assert.h>

template <class T>
class Allocator {
private:
	T       *cache;
	int     size;
	int     currUsed;
    
public:
	Allocator() {
		cache       = NULL;
		size        = 0;
		currUsed    = 0;
	}
    
	~Allocator() {
		release();
	}
    
	void release() {
        if (cache != NULL) {
            delete [] cache;
            cache       = NULL;
            size        = 0;
            currUsed    = 0;
        }
	}
    
	bool init(int size) {
		if (size > this->size){
			T *newCache = new T[size];
			if (newCache == NULL) {
//                printf("\nNot enough memory");
                return false;
            }
			if (currUsed > 0) {
				memcpy(newCache, cache, currUsed * sizeof(T));
			}
            release();
			cache       = newCache;
			this->size  = size;
		}
        return true;
	}
    
	T *getNew() {
		if (currUsed >= size) {
			assert(false && "\nWarning: surprise allocation!!");
			return NULL;
		}
		return &cache[currUsed++];
	}
    
	T       *getCache()             { return cache; }
	T       *getPtr(int index)      { return &cache[index];	}
	T       &get(int index)         { return cache[index]; }
	void    remove()                { currUsed--; }
	void    deallocate()            { currUsed = 0; }
};


#endif // _ALLOCATOR_H_INCLUDED_
